/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Class;
import java.io.File;
import java.util.ArrayList;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

/**
 *
 * @author paintbsd
 */
public class process_XML {
    public static ArrayList<Album> getAlbums(String fileName)
    {
        ArrayList<Album>albums=new ArrayList<Album>();
        try
        {
            
            DocumentBuilderFactory factory =
            DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

        //Here we do the actual parsing
            Document doc = builder.parse(new File(fileName));
            doc.getDocumentElement ().normalize ();
        //Here we get the root element of XML and print out
        //the value of its 'testAttr' attribute
            
            NodeList listOfAlbums = doc.getElementsByTagName("Album");
            int totalAlbums = listOfAlbums.getLength();
            
             for(int s=0; s<totalAlbums ; s++){
                 Node firstPersonNode = listOfAlbums.item(s);
                 
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                        
                    Element firstPersonElement = (Element)firstPersonNode;
                    //-------
                    Album ab;
                    ab = new Album(firstPersonElement.getAttribute("name"),firstPersonElement.getAttribute("date"), firstPersonElement.getAttribute("tieude"), firstPersonElement.getAttribute("mota"), null);
                    ArrayList<String>arrImage=new ArrayList<String>();
                    NodeList listOfFile = firstPersonElement.getElementsByTagName("file");
                    int totalFiles = listOfFile.getLength();
                    for(int s1=0; s1<totalFiles ; s1++){
                        Element file = (Element)listOfFile.item(s1);
                        NodeList textFNList = file.getChildNodes();
                        arrImage.add(((Node)textFNList.item(0)).getNodeValue().trim());
                    }
                    ab.setFiles(arrImage);
                    albums.add(ab);
                    //------
                }//end of if clause
             }
            
            
        }
        catch(Exception ex)
        {
        }
        return albums;
    }
    
    public static boolean writeXML(String fileName)
    {
        
            try {
 
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 
		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("company");
		doc.appendChild(rootElement);
 
		// staff elements
		Element staff = doc.createElement("Staff");
		rootElement.appendChild(staff);
 
		// set attribute to staff element
		Attr attr = doc.createAttribute("id");
		attr.setValue("1");
		staff.setAttributeNode(attr);
 
		// shorten way
		// staff.setAttribute("id", "1");
 
		// firstname elements
		Element firstname = doc.createElement("firstname");
		firstname.appendChild(doc.createTextNode("yong"));
		staff.appendChild(firstname);
 
		// lastname elements
		Element lastname = doc.createElement("lastname");
		lastname.appendChild(doc.createTextNode("mook kim"));
		staff.appendChild(lastname);
 
		// nickname elements
		Element nickname = doc.createElement("nickname");
		nickname.appendChild(doc.createTextNode("mkyong"));
		staff.appendChild(nickname);
 
		// salary elements
		Element salary = doc.createElement("salary");
		salary.appendChild(doc.createTextNode("100000"));
		staff.appendChild(salary);
 
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(fileName));
 
		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);
 
		transformer.transform(source, result);
 
		System.out.println("File saved!");
                return true;
 
	  } catch (ParserConfigurationException pce) {
		return false;
	  } catch (TransformerException tfe) {
		return false;
	  }
            
        }
        
    public static boolean AddAlbumXML(String fileName,Album ab)
    {
        try
        {
            File xmlFile = new File(fileName);
            //Create the documentBuilderFactory
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //Create the documentBuilder
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //Create the Document  by parsing the file
            Document document = documentBuilder.parse(xmlFile);
            //Get the root element of the xml Document;
            Element documentElement = document.getDocumentElement();
            System.out.println("documentElement:" + documentElement.toString());
            //Get childNodes of the rootElement
            //Create a textNode element
            
            //Create a Node element
            Element rootElement = document.createElement("Album");
            //append textNode to Node element;
            //nodeElement.appendChild(textNode);
            Attr attr1=document.createAttribute("name");
            attr1.setValue(ab.getName());
            rootElement.setAttributeNode(attr1);
                
            Attr attr2=document.createAttribute("date");
            attr2.setValue(ab.getDate());
            rootElement.setAttributeNode(attr2);
                
            Attr attr3=document.createAttribute("tieude");
            attr3.setValue(ab.getTitle());
            rootElement.setAttributeNode(attr3);
                
            Attr attr4=document.createAttribute("mota");
            attr4.setValue(ab.getDescription());
            rootElement.setAttributeNode(attr4);
		// staff elements
             
            ArrayList<String>files=ab.getFiles();
            int n=files.size();
            for(int i=0;i<n;i++)
            {
                Element file = document.createElement("file");
                file.appendChild(document.createTextNode(files.get(i)));
		rootElement.appendChild(file);
            }
            //append Node to rootNode element
            documentElement.appendChild(rootElement);
            document.replaceChild(documentElement, documentElement);
            Transformer tFormer =
                    TransformerFactory.newInstance().newTransformer();
//  Set output file to xml
            tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
//  Write the document back to the file
            Source source = new DOMSource(document);
            Result result = new StreamResult(xmlFile);
            tFormer.transform(source, result);

            return true;
        } 
        catch (Exception ex) {
            return false;
        }
    }
     public static boolean EditInfoAlbumXML(String fileName,String oldAlbum,Album ab)
    {
       try
        {
            File xmlFile = new File(fileName);
            //Create the documentBuilderFactory
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //Create the documentBuilder
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //Create the Document  by parsing the file
            Document document = documentBuilder.parse(xmlFile);
            //Get the root element of the xml Document;
            Element documentElement = document.getDocumentElement();
            System.out.println("documentElement:" + documentElement.toString());
            
            NodeList listOfAlbums = document.getElementsByTagName("Album");
            int totalAlbums = listOfAlbums.getLength();
            
             for(int s=0; s<totalAlbums ; s++){
                 Node firstPersonNode = listOfAlbums.item(s);
                 
                    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                        
                        Element firstPersonElement = (Element)firstPersonNode;
                    //-------
                        String str=firstPersonElement.getAttribute("name");
                        if(str.equalsIgnoreCase(oldAlbum))
                        {
                            NamedNodeMap attr = firstPersonElement.getAttributes();
                            Node nameAttr = attr.getNamedItem("name");
                            nameAttr.setTextContent(ab.getName());
                            
                            Node dateAttr = attr.getNamedItem("date");
                            dateAttr.setTextContent(ab.getDate());
                            
                            Node titleAttr = attr.getNamedItem("tieude");
                            titleAttr.setTextContent(ab.getTitle());
                            
                            Node desAttr = attr.getNamedItem("mota");
                            desAttr.setTextContent(ab.getDescription());
                            
                            document.replaceChild(documentElement, documentElement);
                            
                            Transformer tFormer =
                            TransformerFactory.newInstance().newTransformer();
                            //  Set output file to xml
                            tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
                            //  Write the document back to the file
                            Source source = new DOMSource(document);
                            Result result = new StreamResult(xmlFile);
                            tFormer.transform(source, result);
                            return true;
                        }
                    }
             }
             return false;
        } 
        catch (Exception ex) {
            return false;
        }
    }     
    public static boolean AddImageXML(String fileName,String albumName,String files)
    {
        try
        {
            File xmlFile = new File(fileName);
            //Create the documentBuilderFactory
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //Create the documentBuilder
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //Create the Document  by parsing the file
            Document document = documentBuilder.parse(xmlFile);
            //Get the root element of the xml Document;
            Element documentElement = document.getDocumentElement();
            System.out.println("documentElement:" + documentElement.toString());
            
            NodeList listOfAlbums = document.getElementsByTagName("Album");
            int totalAlbums = listOfAlbums.getLength();
            
             for(int s=0; s<totalAlbums ; s++){
                 Node firstPersonNode = listOfAlbums.item(s);
                 
                    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                        
                        Element firstPersonElement = (Element)firstPersonNode;
                    //-------
                        String str=firstPersonElement.getAttribute("name");
                        if(str.equalsIgnoreCase(albumName))
                        {
                            Element file = document.createElement("file");
                            file.appendChild(document.createTextNode(files));
                            firstPersonElement.appendChild(file);
                            document.replaceChild(documentElement, documentElement);
                            Transformer tFormer =
                            TransformerFactory.newInstance().newTransformer();
                            //  Set output file to xml
                            tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
                            //  Write the document back to the file
                            Source source = new DOMSource(document);
                            Result result = new StreamResult(xmlFile);
                            tFormer.transform(source, result);
                            return true;
                        }
                    }
             }
             return false;
        } 
        catch (Exception ex) {
            return false;
        }
    }
    public static boolean RemoveAlbumXML(String fileName,String albumName)
    {
        try
        {
            File xmlFile = new File(fileName);
            //Create the documentBuilderFactory
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //Create the documentBuilder
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //Create the Document  by parsing the file
            Document document = documentBuilder.parse(xmlFile);
            //Get the root element of the xml Document;
            Element documentElement = document.getDocumentElement();
            System.out.println("documentElement:" + documentElement.toString());
            
            NodeList listOfAlbums = document.getElementsByTagName("Album");
            int totalAlbums = listOfAlbums.getLength();
            
             for(int s=0; s<totalAlbums ; s++){
                 Node firstPersonNode = listOfAlbums.item(s);
                 
                    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                        
                        Element firstPersonElement = (Element)firstPersonNode;
                    //-------
                        String str=firstPersonElement.getAttribute("name");
                        if(str.equalsIgnoreCase(albumName))
                        {
                            firstPersonNode.getParentNode().removeChild(firstPersonNode);
                            document.replaceChild(documentElement, documentElement);
                            Transformer tFormer =
                            TransformerFactory.newInstance().newTransformer();
                            //  Set output file to xml
                            tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
                            //  Write the document back to the file
                            Source source = new DOMSource(document);
                            Result result = new StreamResult(xmlFile);
                            tFormer.transform(source, result);
                            return true;
                            
                        }
                    }
             }
            return false;
        } 
        catch (Exception ex) {
            return false;
        }
    }        
    
    public static boolean RemoveImageXML(String fileName,String albumName,String imageName)
    {
        try
        {
            File xmlFile = new File(fileName);
            //Create the documentBuilderFactory
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //Create the documentBuilder
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //Create the Document  by parsing the file
            Document document = documentBuilder.parse(xmlFile);
            //Get the root element of the xml Document;
            Element documentElement = document.getDocumentElement();
            System.out.println("documentElement:" + documentElement.toString());
            
            NodeList listOfAlbums = document.getElementsByTagName("Album");
            int totalAlbums = listOfAlbums.getLength();
            
             for(int s=0; s<totalAlbums ; s++){
                 Node firstPersonNode = listOfAlbums.item(s);
                 
                    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                        
                        Element firstPersonElement = (Element)firstPersonNode;
                    //-------
                        String str=firstPersonElement.getAttribute("name");
                        if(str.equalsIgnoreCase(albumName))
                        {
                            NodeList listOfFile = firstPersonElement.getElementsByTagName("file");
                            int totalFiles = listOfFile.getLength();
                            for(int s1=0; s1<totalFiles ; s1++){
                                Element file = (Element)listOfFile.item(s1);
                                NodeList textFNList = file.getChildNodes();
                                String textNode = ((Node)textFNList.item(0)).getNodeValue().trim();
                                if(textNode.equalsIgnoreCase(imageName))
                                {
                                    file.getParentNode().removeChild(file);
                                    document.replaceChild(documentElement, documentElement);
                                    Transformer tFormer =
                                    TransformerFactory.newInstance().newTransformer();
                                    //  Set output file to xml
                                    tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
                                    //  Write the document back to the file
                                    Source source = new DOMSource(document);
                                    Result result = new StreamResult(xmlFile);
                                    tFormer.transform(source, result);
                                    return true;
                                }
                            }
                        }
                    }
             }
            return false;
        } 
        catch (Exception ex) {
            return false;
        }
    }
    
    public static boolean RenameImageXML(String fileName,String albumName,String OldName,String NewName)
    {
        try
        {
            File xmlFile = new File(fileName);
            //Create the documentBuilderFactory
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //Create the documentBuilder
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            //Create the Document  by parsing the file
            Document document = documentBuilder.parse(xmlFile);
            //Get the root element of the xml Document;
            Element documentElement = document.getDocumentElement();
            System.out.println("documentElement:" + documentElement.toString());
            
            NodeList listOfAlbums = document.getElementsByTagName("Album");
            int totalAlbums = listOfAlbums.getLength();
            
             for(int s=0; s<totalAlbums ; s++){
                 Node firstPersonNode = listOfAlbums.item(s);
                 
                    if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){
                        
                        Element firstPersonElement = (Element)firstPersonNode;
                    //-------
                        String str=firstPersonElement.getAttribute("name");
                        if(str.equalsIgnoreCase(albumName))
                        {
                            NodeList listOfFile = firstPersonElement.getElementsByTagName("file");
                            int totalFiles = listOfFile.getLength();
                            for(int s1=0; s1<totalFiles ; s1++){
                                Element file = (Element)listOfFile.item(s1);
                                NodeList textFNList = file.getChildNodes();
                                String textNode = ((Node)textFNList.item(0)).getNodeValue().trim();
                                if(textNode.equalsIgnoreCase(OldName))
                                {
                                    file.setTextContent(NewName);
                                    document.replaceChild(documentElement, documentElement);
                                    Transformer tFormer =
                                    TransformerFactory.newInstance().newTransformer();
                                    //  Set output file to xml
                                    tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
                                    //  Write the document back to the file
                                    Source source = new DOMSource(document);
                                    Result result = new StreamResult(xmlFile);
                                    tFormer.transform(source, result);
                                    return true;
                                }
                            }
                        }
                    }
             }
            return false;
        } 
        catch (Exception ex) {
            return false;
        }
    }
        
}
